<template>
    <div class="container">
        <Breadcrumb :items="['menu.store', 'menu.store.index']" />
        <a-card :title="$t('menu.store.index')">
            <a-space fill direction="vertical" size="large">

                <!-- 搜索表单 -->
                <a-row>
                    <a-col :flex="1">
                        <a-form :model="searchForm">
                            <a-row :gutter="16">
                                <a-col :span="3">
                                    <a-form-item field="title" label="商品名称" hide-label>
                                        <a-input v-model="searchForm.title" placeholder="请输入商品名称" allow-clear />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="3">
                                    <a-form-item field="cat_id" label="分类" hide-label>
                                        <a-select v-model="searchForm.cat_id" placeholder="请选择分类" allow-clear
                                            @change="onCatChange">
                                            <a-option v-for="cat in categoryList" :key="cat.id" :value="cat.id">
                                                {{ cat.name }}
                                            </a-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="3">
                                    <a-form-item field="sub_cat_id" label="子分类" hide-label>
                                        <a-select v-model="searchForm.sub_cat_id" placeholder="请选择子分类" allow-clear>
                                            <a-option v-for="subCat in subCategoryList" :key="subCat.id"
                                                :value="subCat.id">
                                                {{ subCat.name }}
                                            </a-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="3">
                                    <a-form-item field="second_day" label="秒杀日期" hide-label>
                                        <a-date-picker style="width: 100%" v-model="searchForm.second_day"
                                            placeholder="请选择秒杀日期" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-space>
                                        <a-button type="primary" @click="search">
                                            <template #icon>
                                                <icon-search />
                                            </template>
                                            搜索
                                        </a-button>
                                        <a-button @click="reset">
                                            <template #icon>
                                                <icon-refresh />
                                            </template>
                                            重置
                                        </a-button>
                                    </a-space>
                                </a-col>
                            </a-row>
                        </a-form>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加商品
                            </a-button>
                        </a-space>
                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle" @click="resetSearch">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" :scroll="{ x: 2200 }" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80">
                            <template #cell="{ record }">
                                <div>{{ record.id }}</div>
                                <div style="color: #FF6900;" v-if="record.pre_sale == 1">[预售]</div>
                            </template>
                        </a-table-column>
                        <a-table-column title="图片" data-index="image" :width="80">
                            <template #cell="{ record }">
                                <a-image :src="record.image_url" width="40" />
                            </template>
                        </a-table-column>
                        <a-table-column title="名称" data-index="title" />
                        <a-table-column title="分类" data-index="cat_name" :width="120">
                            <template #cell="{ record }">
                                <a-space direction="vertical" size="mini">
                                    <span v-if="record.cat_name">{{ record.cat_name }}</span>
                                    <span v-if="record.sub_cat_name" style="color: #999; font-size: 12px;">
                                        {{ record.sub_cat_name }}
                                    </span>
                                </a-space>
                            </template>
                        </a-table-column>

                        <a-table-column title="状态" data-index="status" :width="120">
                            <template #cell="{ record }">
                                <a-tag :color="record.status === 'online' ? 'green' : 'red'">{{ record.status ===
                                    'online' ? '上架中' :
                                    '已下架' }}</a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column title="支付订单数" data-index="order_count" :width="120" align="center">
                            <template #cell="{ record }">
                                {{ record.order_count || 0 }}
                            </template>
                        </a-table-column>
                        <a-table-column title="相册图片数" data-index="image_count" :width="120" align="center">
                            <template #cell="{ record }">
                                <a-typography-text type="primary" @click="openAlbumModal(record)" underline>
                                    {{ record.image_count || 0 }}
                                </a-typography-text>
                            </template>
                        </a-table-column>
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="排序" data-index="sort_by" :width="100" />
                        <a-table-column title="秒杀日期" data-index="second_day" :width="120">
                            <template #cell="{ record }">
                                <span
                                    :style="record.second_day === (new Date().toISOString().slice(0, 10)) ? 'color: red;' : ''">
                                    {{ record.second_day || '-' }}
                                </span>
                            </template>
                        </a-table-column>
                        <a-table-column title="操作" align="center" :width="220" fixed="right">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="openSpecModal(record)">
                                        规格
                                    </a-link>
                                    <a-link @click="openKuModal(record)">
                                        库存
                                    </a-link>
                                    <a-link @click="openModal(record)">
                                        编辑
                                    </a-link>
                                    <a-popconfirm position="left" content="确定要删除这个商品吗？" @ok="handleDelete(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" width="1000px" :draggable="true" :title="formData.id ? '编辑商品' : '添加商品'"
            @before-ok="handleSubmit" @cancel="closeModal">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-form-item field="name" label="名字（短）" :rules="[{ required: true }]">
                    <a-input v-model="formData.name" placeholder="请输入名称" />
                </a-form-item>
                <a-form-item field="title" label="标题" :rules="[{ required: true }]">
                    <a-input v-model="formData.title" placeholder="请输入标题" />
                </a-form-item>

                <a-form-item label="图片" :rules="[{ required: true }]">
                    <a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload" :limit="1"
                        :file-list="fileList" image-preview @before-remove="beforeRemove" />
                    <template #extra>
                        <div>请保持图片比例为1:1，格式为jpg/png</div>
                    </template>
                </a-form-item>

                <a-row :gutter="16">
                    <a-col :span="8">
                        <a-form-item field="cat_id" label="分类" :rules="[{ required: true }]">
                            <a-select v-model="formData.cat_id" placeholder="请选择分类" @change="onFormCatChange">
                                <a-option v-for="cat in categoryList" :key="cat.id" :value="cat.id">
                                    {{ cat.name }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="sub_cat_id" label="子分类">
                            <a-select v-model="formData.sub_cat_id" placeholder="请选择子分类" allow-clear>
                                <a-option v-for="subCat in formSubCategoryList" :key="subCat.id" :value="subCat.id">
                                    {{ subCat.name }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="sort_by" label="排序" :rules="[{ required: true }]">
                            <a-input-number v-model="formData.sort_by" placeholder="请输入排序" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="status" label="状态" :rules="[{ required: true }]">
                            <a-select v-model="formData.status" placeholder="请选择状态">
                                <a-option value="online">上架中</a-option>
                                <a-option value="offline">已下架</a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="second_day" label="秒杀日期" :rules="[{ required: true }]">
                            <a-date-picker v-model="formData.second_day" style="width:100%;"
                                placeholder="如果不秒数则不需要输入" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="recommend_day" label="推荐日期" :rules="[{ required: true }]">
                            <a-date-picker v-model="formData.recommend_day" style="width:100%;"
                                placeholder="如果不推荐则不需要输入" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="pre_sale" label="销售方式" :rules="[{ required: true }]">
                            <a-select v-model="formData.pre_sale" placeholder="必需选择">
                                <a-option value="0">现售商品</a-option>
                                <a-option value="1">预售商品</a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <template v-if="formData.pre_sale == 1">
                        <a-col :span="8">
                            <a-form-item field="pre_sale_start_at" label="预售开始时间" :rules="[{ required: true }]">
                                <a-date-picker v-model="formData.pre_sale_start_at" style="width:100%;"
                                    placeholder="请选择预售开始时间" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item field="pre_sale_end_at" label="预售结束时间" :rules="[{ required: true }]">
                                <a-date-picker v-model="formData.pre_sale_end_at" style="width:100%;"
                                    placeholder="请选择预售结束时间" />
                            </a-form-item>
                        </a-col>
                    </template>
                </a-row>
                <a-form-item field="desc" label="商品详情">
                    <div class="markdown-editor-container">
                        <v-md-editor v-model="formData.content" @upload-image="handleUploadImage" :disabled-menus="[]"
                            height="300px" style="width: 100%;" />
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>

        <a-modal v-model:visible="specModalVisible" width="700px" :draggable="true" title="规格管理"
            @cancel="closeSpecModal">
            <template #footer>
                <a-button shape="round" type="primary" @click="handleAddSpec">
                    添加规格
                </a-button>
            </template>
            <a-typography-paragraph>
                <ol>
                    <li>对规格值进行编辑后会对库存对应的规格值进行批量更新</li>
                    <li>
                        <a-typography-text type="danger" underline>当删除一个规格值时，并不会对已经存在的库存进行删除</a-typography-text>
                    </li>
                </ol>
            </a-typography-paragraph>
            <a-space direction="vertical" fill size="large">
                <a-card header-style="background:#F9F9F9;" v-for="spec in goodsSpecsData" :key="spec.id"
                    :title="`【${spec.spec_name}】`" hoverable>
                    <template #extra>
                        <a-link @click="handleAddSpecValue(spec.id)">
                            添加规格值
                        </a-link>
                    </template>

                    <a-space size="large">
                        <a-tag v-for="value in spec.spec_values" :key="value" size="large" :bordered="true"
                            @click="handleEditSpecValue(spec.id, value)">
                            <template #icon>
                                <icon-edit />
                            </template>
                            {{ value }}
                        </a-tag>
                    </a-space>
                </a-card>
            </a-space>
        </a-modal>

        <a-modal v-model:visible="addSpecValueVisible" width="500px" :draggable="true"
            :title="isEditSpecValue ? '编辑规格值' : '添加规格值'" @cancel="closeAddSpecValue">
            <a-form :model="addSpecValueForm" ref="addSpecValueFormRef" layout="vertical">
                <a-form-item field="spec_value" label="规格值" :rules="[{ required: true, message: '请输入规格值' }]">
                    <a-input v-model="addSpecValueForm.spec_value" placeholder="请输入规格值" />
                </a-form-item>
            </a-form>
            <template #footer>
                <a-space>
                    <template v-if="isEditSpecValue" #split>
                        <a-divider direction="vertical" />
                    </template>
                    <a-popconfirm content="确定要删除这个规格值吗？" type="error" position="left" @ok="doDeleteSpecValue">
                        <a-button shape="round" type="primary" status="danger" v-if="isEditSpecValue">删除</a-button>
                    </a-popconfirm>
                    <a-button shape="round" type="primary" @click="doAddSpecValue">确定</a-button>
                </a-space>

            </template>
        </a-modal>

        <a-modal v-model:visible="addSpecFormVisible" width="400px" :draggable="true" title="添加规格"
            @cancel="closeAddSpecForm" @before-ok="doAddSpec">
            <a-form :model="addSpecFormData" ref="addSpecFormRef" layout="vertical">
                <a-form-item field="spec_name" label="规格名称" :rules="[{ required: true, message: '请输入规格名称' }]">
                    <a-input v-model="addSpecFormData.spec_name" placeholder="请输入规格名称" />
                </a-form-item>
            </a-form>
        </a-modal>

        <a-modal v-model:visible="kuModalVisible" width="1000px" :draggable="true" title="库存管理" @cancel="closeKuModal">
            <template #footer>
                <a-button shape="round" type="primary" @click="handleAddKu">添加库存项</a-button>
            </template>
            <div>
                <a-table :data="renderSkuData" :loading="loading" :bordered="{ cell: true }" pagination="false">
                    <template #columns>
                        <a-table-column title="库存ID" data-index="id" :width="100" />
                        <a-table-column title="库存名称" data-index="name" />
                        <a-table-column title="规格" data-index="specs">
                            <template #cell="{ record }">
                                <a-space>
                                    <a-tag v-for="spec in record.specs" :key="spec" :bordered="true">
                                        {{ spec }}
                                    </a-tag>
                                </a-space>
                            </template>
                        </a-table-column>   
                        <a-table-column title="价格" data-index="price" :width="100" />
                        <a-table-column title="库存数量" data-index="v" :width="120" />
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="操作" fixed="right" data-index="action" :width="120">
                            <template #cell="{ record }">
                                <a-link @click="handleEditKu(record.id)">编辑</a-link>
                                <a-popconfirm content="确定要删除这个库存项吗？" type="error" position="left" @ok="handleDeleteKu(record.id)">
                                    <a-link type="primary" status="danger">删除</a-link>
                                </a-popconfirm>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </div>
        </a-modal>

        <a-modal v-model:visible="submitKuVisible" width="650px" :draggable="true" :title="kuForm.id ? '编辑库存项（SKU）' : '添加库存项（SKU）'" @cancel="closeKu" @before-ok="doSubmitKu">
            <a-form :model="kuForm" ref="kuFormRef" layout="vertical">
                <a-form-item field="name" label="名称" :rules="[{ required: true, message: '请输入名称' }]">
                    <a-input v-model="kuForm.name" placeholder="请输入名称（SKU）" />
                </a-form-item>
                <a-row  :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="price" label="价格" :rules="[{ required: true, message: '请输入价格' }]">
                            <a-input v-model="kuForm.price" placeholder="请输入价格" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="v" label="库存数量" :rules="[{ required: true, message: '请输入数量' }]">
                            <a-input v-model="kuForm.v" placeholder="请输入数量" />
                        </a-form-item>
                    </a-col>
                </a-row>
                
                <!-- 规格选择 -->
                <a-form-item label="规格配置" v-if="goodsSpecsData && goodsSpecsData.length > 0">
                    <a-space direction="vertical" fill>
                        <div v-for="spec in goodsSpecsData" :key="spec.id" style="padding: 12px;width:610px;background: #f7f8fa; border-radius: 4px;">
                            <div style="margin-bottom: 8px; font-weight: 500; color: #1d2129;">
                                {{ spec.spec_name }}
                            </div>
                            <a-radio-group 
                                v-model="selectedSpecs[spec.spec_name]"
                                @change="updateKuSpecs">
                                <a-radio 
                                    v-for="value in spec.spec_values" 
                                    :key="value" 
                                    :value="value">
                                    {{ value }}
                                </a-radio>
                            </a-radio-group>
                        </div>
                    </a-space>
                </a-form-item>
                
            </a-form>
        </a-modal>

        <a-modal v-model:visible="albumModalVisible" width="900px" :footer="false" :draggable="true" title="商品相册管理"
            @cancel="closeAlbumModal">
            <div v-if="currentGoods">
                <a-space direction="vertical" fill size="large">
                    <!-- 相册头部信息 -->
                    <a-card size="small">
                        <a-space>
                            <a-image :src="currentGoods.image_url" :width="100" :height="100" fit="cover" />
                            <div>
                                <a-typography-title :heading="4">
                                    [{{ currentGoods.id }}]{{ currentGoods.title }}
                                </a-typography-title>
                            </div>
                        </a-space>
                    </a-card>

                    <!-- 添加图片 -->
                    <a-card size="small" title="添加图片">
                        <a-space direction="vertical" fill>
                            <a-upload list-type="picture-card" :custom-request="handleAlbumUpload" :limit="10"
                                :file-list="albumFileList" image-preview @before-remove="beforeAlbumRemove"
                                accept="image/*">
                                <template #upload-button>
                                    <a-button type="primary" shape="round">
                                        <template #icon><icon-plus /></template>
                                        点击上传图片
                                    </a-button>
                                </template>
                            </a-upload>
                            <div>支持jpg、png格式，建议尺寸800x800</div>
                        </a-space>
                    </a-card>

                    <!-- 相册列表 -->
                    <a-card size="small" title="相册列表">
                        <a-row :gutter="24" :loading="albumLoading">
                            <a-col :span="12" v-for="item in albumList" :key="item.id">
                                <a-space>
                                    <a-image :src="item.url" :width="80" :height="80" fit="cover" />
                                    <div style="flex: 1;">
                                        <a-input v-model="item.title" placeholder="图片标题" size="small" />
                                        <div style="margin-top: 8px;">
                                            <a-space>
                                                <a-button size="mini" shape="round"
                                                    @click="updateImageInfo(item)">保存</a-button>
                                                <a-popconfirm content="确定要删除这张图片吗？" @ok="deleteImage(item.id)">
                                                    <a-button size="mini" shape="round" status="danger">删除</a-button>
                                                </a-popconfirm>
                                            </a-space>
                                        </div>
                                    </div>
                                </a-space>
                            </a-col>
                        </a-row>

                    </a-card>
                </a-space>
            </div>
        </a-modal>
    </div>
</template>


<style scoped>
.markdown-editor-container {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    width: 100%;
}

.markdown-editor-container :deep(.v-md-editor) {
    border: none;
    width: 100%;
}

.markdown-editor-container :deep(.v-md-editor__toolbar) {
    border-bottom: 1px solid #f0f0f0;
}

.markdown-editor-container :deep(.v-md-editor__editor-wrapper) {
    border: none;
    width: 100%;
}
</style>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption, FileItem } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import {
    queryGoodsList,
    submitGoodsForm,
    delGoods,
    GoodsRecord,
    queryGoodsSpecs,
    addGoodsSpec,
    addGoodsSpecValue,
    queryGoodsKu,
    saveGoodsKu,
    SkuData,
    queryGoodsImages,
    addGoodsImage,
    delGoodsImage,
    updateGoodsImage,
    GoodsImageRecord,
    delGoodsSpecValue,
    delGoodsKu
} from '@/api/goods';
import { getGoodsCatList, GoodsCatItem } from '@/api/goodsCat';
import { uploadFile, UploadResponse } from '@/api/upload';

import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import createEmojiPlugin from '@kangc/v-md-editor/lib/plugins/emoji/index';
import '@kangc/v-md-editor/lib/plugins/emoji/emoji.css';
import createTodoListPlugin from '@kangc/v-md-editor/lib/plugins/todo-list/index';
import '@kangc/v-md-editor/lib/plugins/todo-list/todo-list.css';
import createAlignPlugin from '@kangc/v-md-editor/lib/plugins/align/index';
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index';
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index';
import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';
import createHighlightLinesPlugin from '@kangc/v-md-editor/lib/plugins/highlight-lines/index';
import '@kangc/v-md-editor/lib/plugins/highlight-lines/highlight-lines.css';

const { loading, setLoading } = useLoading(false);
const modalVisible = ref(false);
const formRef = ref();
const fileList = ref<FileItem[]>([]);

// 配置v-md-editor
VMdEditor.use(githubTheme);
VMdEditor.use(createEmojiPlugin());
VMdEditor.use(createTodoListPlugin());
VMdEditor.use(createAlignPlugin());
VMdEditor.use(createLineNumbertPlugin());
VMdEditor.use(createCopyCodePlugin());
VMdEditor.use(createHighlightLinesPlugin());

// 搜索表单
const searchForm = reactive({
    current: 1,
    pageSize: 10,
    title: '',
    cat_id: '',
    sub_cat_id: '',
    second_day: '',
});

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

const generateFormData = () => {
    return {
        id: 0,
        title: '',
        name: '',
        image: '',
        sort_by: 0,
        status: 'online',
        cat_id: '',
        sub_cat_id: '',
        second_day: '',
        recommend_day: '',
        content: '',
        pre_sale: '',
        pre_sale_start_at: '',
        pre_sale_end_at: '',
    };
};

const formData = ref(generateFormData());

const renderData = ref<GoodsRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryGoodsList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            title: searchForm.title,
            cat_id: searchForm.cat_id,
            sub_cat_id: searchForm.sub_cat_id,
            second_day: searchForm.second_day,
            recommend_day: searchForm.recommend_day,
        });
        renderData.value = data.list;
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取商品列表失败');
    } finally {
        setLoading(false);
    }
};

const search = () => {
    searchForm.current = 1;
    pagination.current = 1;
    fetchData();
};

const reset = () => {
    searchForm.title = '';
    searchForm.cat_id = 0;
    searchForm.sub_cat_id = 0;
    search();
};

const onPageChange = (current: number) => {
    pagination.current = current;
    searchForm.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const openModal = (record?: GoodsRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            title: record.title,
            name: record.name,
            image: record.image,
            sort_by: record.sort_by,
            status: record.status || 'online',
            cat_id: record.cat_id || '',
            sub_cat_id: record.sub_cat_id || '',
            second_day: record.second_day || '',
            recommend_day: record.recommend_day || '',
            content: record.content || '',
            pre_sale: record.pre_sale || '0',
            pre_sale_start_at: record.pre_sale_start_at || '',
            pre_sale_end_at: record.pre_sale_end_at || '',
        };
        fileList.value = [{ uid: '1', url: record.image_url || '' } as FileItem];

        // 如果编辑时有分类，需要设置子分类选项
        if (record.cat_id) {
            onFormCatChange(record.cat_id);
        }
    } else {
        formData.value = generateFormData();
        fileList.value = [];
        formSubCategoryList.value = [];
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
};

const handleUpload = (option: RequestOption): UploadRequest => {
    const { onProgress, onError, onSuccess, fileItem } = option;

    const uploadFormData = new FormData();
    uploadFormData.append('file', fileItem.file as File);

    uploadFile(uploadFormData).then(({ data }) => {
        formData.value.image = data.url;
        fileList.value = [{ url: data.url } as FileItem];
        Message.success('上传成功');
        onSuccess?.(data);
    }).catch((err) => {
        Message.error('上传失败');
        onError?.(err);
    });

    return {
        abort: () => { },
    };
};


// 富媒体编辑框图片上传方法
const handleUploadImage = async (event: any, insertImage: any) => {
    try {
        // 创建文件输入元素
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';

        input.onchange = async (e: any) => {
            const file = e.target.files[0];
            if (!file) {
                Message.warning('请选择要上传的图片');
                return;
            }

            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                Message.error('只能上传图片文件');
                return;
            }

            // 检查文件大小（限制为5MB）
            const maxSize = 5 * 1024 * 1024; // 5MB
            if (file.size > maxSize) {
                Message.error('图片大小不能超过5MB');
                return;
            }

            try {
                const uploadFormData = new FormData();
                uploadFormData.append('file', file);

                const { data } = await uploadFile(uploadFormData);

                // 插入图片到编辑器
                insertImage({
                    url: data.url,
                    alt: file.name,
                    title: file.name
                });

                Message.success('图片上传成功');
            } catch (err) {
                console.error('图片上传失败:', err);
                Message.error('图片上传失败，请重试');
            }
        };

        // 触发文件选择
        input.click();
    } catch (err) {
        console.error('图片上传失败:', err);
        Message.error('图片上传失败，请重试');
    }
};

const beforeRemove = async (fileItem: FileItem): Promise<boolean> => {
    formData.value.image = '';
    fileList.value = [];
    return true;
};

const handleSubmit = async (done: (closed: boolean) => void) => {
    setLoading(true);
    try {
        const res = await submitGoodsForm(formData.value);
        Message.success('操作成功');
        closeModal();
        fetchData();
        done(true);
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delGoods(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

const resetSearch = () => {
    searchForm.title = '';
    searchForm.cat_id = 0;
    searchForm.sub_cat_id = 0;
    subCategoryList.value = [];
    pagination.current = 1;
    searchForm.current = 1;
    fetchData();
};

const currentGoods = ref<GoodsRecord | null>(null);
const goodsSpecsData = ref<any[]>([]);
const fetchGoodsSpecs = async () => {
    if (!currentGoods.value) return;
    const { data } = await queryGoodsSpecs(currentGoods.value.id);
    goodsSpecsData.value = data.specs;
};
const specModalVisible = ref(false);
const openSpecModal = (record: GoodsRecord) => {
    specModalVisible.value = true;
    currentGoods.value = record;
    fetchGoodsSpecs();
};

const closeSpecModal = () => {
    specModalVisible.value = false;
};

// 添加规格
const addSpecFormData = ref({
    goods_id: 0,
    spec_name: ''
});
const addSpecFormVisible = ref(false);
const handleAddSpec = () => {
    addSpecFormVisible.value = true;
};

const closeAddSpecForm = () => {
    addSpecFormVisible.value = false;
};

const doAddSpec = async (done: any) => {
    setLoading(true);
    if (!currentGoods.value) return;
    addSpecFormData.value.goods_id = currentGoods.value.id;
    await addGoodsSpec(addSpecFormData.value).then(() => {
        Message.success('添加规格成功');
        closeAddSpecForm();
        fetchGoodsSpecs();
        done(true);

        setLoading(false);
    }).catch((err) => {
        done(false);
        setLoading(false);
    });
};

// 添加规格值
const currentSpecId = ref(0);
const addSpecValueForm = ref({
    goods_id: 0,
    spec_id: 0,
    spec_value: '',
    is_edit: false,
    selected_spec_value: ''
});

const addSpecValueVisible = ref(false);
const handleAddSpecValue = (specId: number) => {
    addSpecValueVisible.value = true;
    currentSpecId.value = specId;
    addSpecValueForm.value.spec_value = '';
    addSpecValueForm.value.is_edit = false;
    addSpecValueForm.value.selected_spec_value = '';

    currentSelectSpecValue.value = '';
    isEditSpecValue.value = false;
};

const closeAddSpecValue = () => {
    addSpecValueVisible.value = false;
};

const isEditSpecValue = ref(false);
const currentSelectSpecValue = ref('');
const handleEditSpecValue = (specId: number, value: string) => {
    addSpecValueVisible.value = true;
    currentSpecId.value = specId;

    addSpecValueForm.value.spec_value = value;
    addSpecValueForm.value.is_edit = true;
    addSpecValueForm.value.selected_spec_value = value;

    currentSelectSpecValue.value = value;
    isEditSpecValue.value = true;
};

const doAddSpecValue = async (done: any) => {
    if (!currentGoods.value) return;
    addSpecValueForm.value.goods_id = currentGoods.value.id;
    addSpecValueForm.value.spec_id = currentSpecId.value;
    await addGoodsSpecValue(addSpecValueForm.value).then(() => {
        Message.success('提交规格值成功');
        closeAddSpecValue();
        fetchGoodsSpecs();
        done(true);

    }).catch((err) => {
        done(false);
    });
};

/**
 * 删除规格
 */
const doDeleteSpecValue = async () => {
    await delGoodsSpecValue({
        goods_id: currentGoods.value.id,
        spec_id: currentSpecId.value,
        spec_value: currentSelectSpecValue.value
    }).then(() => {
        Message.success('删除规格值成功');
        closeAddSpecValue();
        fetchGoodsSpecs();
    }).catch((err) => {
        Message.error('删除规格值失败');
    });

};

// 库存管理
const kuModalVisible = ref(false);
const renderSkuData = ref([]);
const fetchGoodsKu = async () => {
    if (!currentGoods.value) return;
    try {
        const { data } = await queryGoodsKu(currentGoods.value.id);
        renderSkuData.value = data.kus;
    } catch (err) {
        Message.error('获取SKU数据失败');
    }
};

const openKuModal = (record: GoodsRecord) => {
    kuModalVisible.value = true;
    currentGoods.value = record;
    fetchGoodsKu();
};

const closeKuModal = () => {
    kuModalVisible.value = false;
};

const kuForm = ref({});
const generateKuForm = () => {
    return {
        id: 0,
        goods_id:0,
        name: '',
        specs: [],
        v: 0,
        price: 0
    }
};

// 规格选择相关
const selectedSpecs = ref<Record<string, string>>({});

// 更新库存表单的specs字段
const updateKuSpecs = () => {
    // 将 selectedSpecs 转换为 [{name:"规格名", value:"值"}] 的数组格式
    const specsArray = Object.entries(selectedSpecs.value).map(([specName, specValue]) => {
        return { name: specName, value: specValue };
    });
    kuForm.value.specs = specsArray;
};

const submitKuVisible = ref(false);
const handleAddKu = async () => {
    submitKuVisible.value = true;
    kuForm.value = generateKuForm();
    // 重置规格选择
    selectedSpecs.value = {};
    // 加载商品规格数据
    await fetchGoodsSpecs();
}

// 编辑库存项
const handleEditKu = async (id: number) => {
    // 从 renderSkuData 中找到对应的库存项
    const skuItem = renderSkuData.value.find((item: any) => item.id === id);
    if (!skuItem) {
        Message.error('未找到该库存项');
        return;
    }
    
    // 填充表单数据
    kuForm.value = {
        id: skuItem.id,
        goods_id: skuItem.goods_id,
        name: skuItem.name,
        specs: skuItem.specs_data || skuItem.specs || [],
        v: skuItem.v,
        price: skuItem.price
    };
    
    // 重置规格选择
    selectedSpecs.value = {};
    
    // 加载商品规格数据
    await fetchGoodsSpecs();
    
    // 根据SKU的specs_data恢复规格选择状态
    if (skuItem.specs_data && Array.isArray(skuItem.specs_data)) {
        skuItem.specs_data.forEach((spec: any) => {
            if (typeof spec === 'object' && spec.name && spec.value) {
                selectedSpecs.value[spec.name] = spec.value;
            }
        });
    } else if (skuItem.specs && Array.isArray(skuItem.specs)) {
        // 兼容旧的 specs 字段
        skuItem.specs.forEach((spec: any) => {
            if (typeof spec === 'object' && spec.name && spec.value) {
                selectedSpecs.value[spec.name] = spec.value;
            }
        });
    }
    
    // 打开弹框
    submitKuVisible.value = true;
}

const closeKu = async () => {
    submitKuVisible.value = false;
}

const doSubmitKu = async (done: any) => {
    if (!currentGoods.value) return;
    kuForm.value.goods_id = currentGoods.value.id;
    await saveGoodsKu({
        sku_data: kuForm.value
    }).then(() => {
        Message.success(kuForm.value.id ? '编辑库存项成功' : '添加库存项成功');
        closeKu();
        fetchGoodsKu(); // 刷新库存列表
        done(true);
    }).catch((err) => {
        Message.error('提交库存项失败');
        done(false);
    });
}

// 删除一个库存项
const handleDeleteKu = async (id: number) => {
    await delGoodsKu({ id }).then(() => {
        Message.success('删除库存项成功');
        fetchGoodsKu();
    }).catch((err) => {
        Message.error('删除库存项失败');
    });
}

// 相册相关方法
const openAlbumModal = async (record: GoodsRecord) => {
    currentGoods.value = record;
    albumModalVisible.value = true;
    await fetchAlbumList(record.id);
};

const closeAlbumModal = () => {
    albumModalVisible.value = false;
    currentGoods.value = null;
    albumList.value = [];
    albumFileList.value = [];
};

const fetchAlbumList = async (goodsId: number) => {
    albumLoading.value = true;
    try {
        const { data } = await queryGoodsImages({ goods_id: goodsId });
        albumList.value = data;
    } catch (err) {
        Message.error('获取相册列表失败');
    } finally {
        albumLoading.value = false;
    }
};

const handleAlbumUpload = (option: RequestOption): UploadRequest => {
    const { onProgress, onError, onSuccess, fileItem } = option;

    const uploadFormData = new FormData();
    uploadFormData.append('file', fileItem.file as File);

    uploadFile(uploadFormData).then(async ({ data }) => {
        if (currentGoods.value) {
            try {
                await addGoodsImage({
                    goods_id: currentGoods.value.id,
                    path: data.path,
                    title: '',
                    sort: albumList.value.length
                });
                Message.success('添加图片成功');
                await fetchAlbumList(currentGoods.value.id);
                albumFileList.value = [];
                onSuccess?.(data);
            } catch (err) {
                Message.error('添加图片失败');
                onError?.(err);
            }
        }
    }).catch((err) => {
        Message.error('上传失败');
        onError?.(err);
    });

    return {
        abort: () => { },
    };
};

const beforeAlbumRemove = async (fileItem: FileItem): Promise<boolean> => {
    return true;
};

const deleteImage = async (imageId: number) => {
    try {
        await delGoodsImage(imageId);
        Message.success('删除成功');
        if (currentGoods.value) {
            await fetchAlbumList(currentGoods.value.id);
        }
    } catch (err) {
        Message.error('删除失败');
    }
};

const updateImageInfo = async (image: GoodsImageRecord) => {
    try {
        await updateGoodsImage({
            id: image.id,
            title: image.title,
            sort: image.sort,
            path: image.path,
            goods_id: image.goods_id
        });
        Message.success('更新成功');
    } catch (err) {
        Message.error('更新失败');
    }
};

// 相册相关变量
const albumModalVisible = ref(false);
const albumFileList = ref<FileItem[]>([]);
const albumLoading = ref(false);
const albumList = ref<GoodsImageRecord[]>([]);

// 分类和子分类列表
const categoryList = ref<GoodsCatItem[]>([]);
const subCategoryList = ref<GoodsCatItem[]>([]);
const formSubCategoryList = ref<GoodsCatItem[]>([]);

const fetchCategoryList = async () => {
    try {
        const res = await getGoodsCatList();
        if (res.code === 20000) {
            categoryList.value = res.data.list;
        } else {
            Message.error('获取分类列表失败');
        }
    } catch (err) {
        Message.error('获取分类列表失败');
    }
};

const onCatChange = (value: number) => {
    searchForm.sub_cat_id = 0; // 当分类改变时，重置子分类
    subCategoryList.value = [];
    if (value > 0) {
        // 从分类列表中查找子分类
        const selectedCat = categoryList.value.find(cat => cat.id === value);
        if (selectedCat && selectedCat.children) {
            subCategoryList.value = selectedCat.children;
        }
    }
    searchForm.current = 1;
    pagination.current = 1;
    fetchData();
};

const onFormCatChange = (value: number) => {
    formData.value.sub_cat_id = 0; // 当分类改变时，重置子分类
    formSubCategoryList.value = [];
    if (value > 0) {
        // 从分类列表中查找子分类
        const selectedCat = categoryList.value.find(cat => cat.id === value);
        if (selectedCat && selectedCat.children) {
            formSubCategoryList.value = selectedCat.children;
        }
    }
};

onMounted(() => {
    fetchData();
    fetchCategoryList();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}

.empty-sku {
    text-align: center;
    padding: 40px 0;
}

.sku-table-container {
    .arco-table {
        .arco-table-th {
            background-color: #f7f8fa;
            font-weight: 600;
        }

        .arco-table-td {
            padding: 8px 12px;
        }
    }
}

.empty-album {
    text-align: center;
    padding: 40px 0;
}

.album-image-container {
    padding: 20px;
}
</style>

<script lang="ts">
export default {
    name: 'StoreIndex',
};
</script>